"""
Run this file to run the game.
"""

####IMPORTS####
import pygame, os
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,600))#pygame.display.set_mode((800,600), FULLSCREEN)
from qnd import *
from roy import Roy
from buildings import load_buildings, Building
import items

####CONSTANTS####
FRAMERATE = 30
SPLASH_DELAY = 300#milliseconds to show the opening splash screen
SOLID_TILES = [2,3,15]#The tiles that Roy will collide with
fonts = {'main':pygame.font.Font(None,24)}
####FUNCTIONS####
def play_level(level):
	"""Playes the level"""
	clock = pygame.time.Clock()
	roy = Roy((100,100))

	#Create the main map from all the map files
	mainmap = load_mainmap()
	mainmappos = [0,0] #The current position on the main map
	print mainmappos
	
	tilemap,collision_map,buildings = get_mainmap(mainmap,mainmappos)#load data from main map
	
	tileset = load_tileset('tileset_1.png')

	camera = Camera(screen)
	camera.x = -(screen.get_width()-tileset[0].get_width()*len(tilemap))/2
	camera.y = -(screen.get_height()-tileset[0].get_height()*len(tilemap[0]))/2
	
	squarewidth = tileset[0].get_width()*len(tilemap)
	squareheight = tileset[0].get_height()*len(tilemap[0])
	
	
	#starting inventory
	roy.give_item(items.HealthPotion())
	
	
	#The main loop
	while True:
		#Update Objects
		input.update()
		roy.update(input,tilemap,collision_map)
		
		
		#Move Roy to next square in the mainmap when at the edge of the screen
		if roy.x < 0 and mainmappos[0] > 0:
			mainmappos[0] -= 1
			tilemap,collision_map,buildings = get_mainmap(mainmap,mainmappos)
			roy.x = squarewidth-1
		elif roy.x > squarewidth and mainmappos[0] < len(mainmap)-1:
			mainmappos[0] += 1
			tilemap,collision_map,buildings = get_mainmap(mainmap,mainmappos)
			roy.x = 1
		if roy.y < 0 and mainmappos[1] > 0:
			mainmappos[1] -= 1
			tilemap,collision_map,buildings = get_mainmap(mainmap,mainmappos)
			roy.y = squareheight-1
		elif roy.y > squareheight and mainmappos[1] < len(mainmap[mainmappos[1]])-1:
			mainmappos[1] += 1
			tilemap,collision_map,buildings = get_mainmap(mainmap,mainmappos)
			roy.y = 1	
		
		
		###DRAWING###
		screen.fill((0,0,0))
		draw_tiles(screen, tilemap, tileset,camera)
		pygame.draw.rect(screen,(0,0,0),(-camera.x,-camera.y,squarewidth,squareheight), 4)

		for building in buildings:
			building.draw(screen,camera)
		roy.draw(screen,camera)
		
		if input.keys[K_e] or input.keys[K_i]:
			roy.draw_inventory(screen)

		##DEBUGGING STUFF
		#Draw Hud
		draw_text(screen, "Map: "+str(mainmappos),(10,10),fonts['main'],(255,255,255))
		draw_text(screen, "Tile: "+str(get_tile_position((roy.x,roy.y))),(10,30),fonts['main'],(255,255,255))
		draw_text(screen, "Coordinate: "+str((roy.x,roy.y)),(10,50),fonts['main'],(255,255,255))
		#~ draw_tiles(screen, collision_map, tileset,camera) ###Draw the collision map for debugging

		#refresh the screen
		pygame.display.flip()
		
		#Limit the framerate
		clock.tick(FRAMERATE)


def get_mainmap(mainmap,(x,y)):
	"""
	Returns a tuple with the tilemap, collision map and list of
	buildings at the position on the main map.
	"""
	tilemap = mainmap[x][y][0] #the tilemap for the current square of the big map
	collision_map = mainmap[x][y][1] #the boolean list of collisions for tiles
	buildings = mainmap[x][y][2] #the list of buildings
	return tilemap,collision_map,buildings

def load_mainmap():
	mainmap = [] #map that contains tiles
	for i in range(11):
		main_column = []
		for j in range(11):
			#the number that references the file
			file_number = str(i).zfill(2)+str(j).zfill(2)
			#load the tilemap
			tiles = load_tilemap(file_number)
			#load the buildings
			buildings = load_buildings(file_number)
			#create a collision map from the tilemap
			collision = []
			for tile_column in tiles:
				collision_column = []
				for tile in tile_column:
					collision_column.append(tile in SOLID_TILES)
				collision.append(list(collision_column))
			if buildings:
				for building in buildings:
					for k in range(building.x,building.x+building.width):
						for l in range(building.y,building.y+building.height):
							try:
								collision[k][l] = True
							except IndexError:
								pass
			main_column.append((tiles,collision,buildings))
		mainmap.append(main_column)

	return mainmap
####INITIALIZE####
input = InputHandler()
screen.fill((120,40,40))
draw_text(screen, "ROY", ('c','c'),pygame.font.Font(None,240))
pygame.display.flip()
pygame.time.wait(SPLASH_DELAY)
draw_text(screen, "Loading Maps", ('c',600),pygame.font.Font(None,48))
pygame.display.flip()
play_level("level_1")
